package controller;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import util.ResultUtil;

public class SensorServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		String hname = request.getParameter("hname");
		String clevel = request.getParameter("clevel");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		Map<String, Object> map = new HashMap<String, Object>();
		Gson gson = new Gson();
		// map.put("resultCode", "999");

		String url = "python /home/pi/efeelture_hardware/" + hname + ".py " + clevel;
		// CtrlRW.runShell(url);
		// out.write(CtrlServlet.class.
		// getResource("/").
		// getPath());
		// String url = "cd ..&&chmod 777 *&&./shell/hardware.sh " + hname + " " +
		// clevel;
		// String url = "/Users/drallin/zs.sh " + hname + " " + clevel;
		// out.write(url);
		try {
			Process process = Runtime.getRuntime().exec(url);
			InputStreamReader ir = new InputStreamReader(process.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			String resultstr = "";
			String line = "";
			while ((line = input.readLine()) != null) {
				resultstr = resultstr + line;

			}
			// out.write(resultstr);
			// System.out.println(line);
			input.close();
			ir.close();
			map.put("resultCode", "999");
			map.put("content", resultstr);
			String resultCode = gson.toJson(map);
			out.write(resultCode);
		} catch (IOException e) {
			String resultCode = ResultUtil.getCtrlErrorCode();
			out.write(resultCode);
			e.printStackTrace();
		}

	}
}
